package com.swq.java.code.chapter13.code23;

/**
 * 为了保证子线程run方法先执行
 * 做了一些调整，否则执行结果和书上不一致
 */
public class Machine extends Thread {
    private int a = 1;

    public synchronized void print() {
        System.out.println("a=" + a);
    }

    public void run() {
        synchronized (this) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("run method");
            a = 1 / 0;  //抛出ArithmeticException
            a++;
        }
    }

    public static void main(String args[]) throws InterruptedException {
        Machine machine = new Machine();
        machine.start();
        Thread.yield();
        // 这里让主线程sleep一段时间（比machine线程短），保证输出结果准确
        Thread.sleep(1000);
        machine.print();
    }
}